<template>
  <div>
    <CommonDialog class="pagemaker-links">
      <div slot="title">{{ title }}</div>
      <section slot="content">
        <el-container>
          <el-aside width="180px">
            <ul>
              <li
                v-for="item in list"
                :key="item.value"
                :class="{'active': item.value == active}"
                @click="handleToggle(item)"
              >{{ item.label }}
              </li>
            </ul>
          </el-aside>
          <el-main>
            <template v-if="active == 'outside' ">
              <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="链接名称" prop="name">
                  <el-input v-model.trim="form.name" :maxlength="50" placeholder="输入链接名称" />
                </el-form-item>
                <el-form-item label="链接地址" prop="link">
                  <el-input v-model.trim="form.link" placeholder="输入链接地址" />
                </el-form-item>
                <section class="tip">
                  <template v-if="active == 'outside'">
                    <div style="color: red;">跳转外部链接，例：“https://www.baidu.com”</div>
                  </template>
                  <template v-else />
                </section>
              </el-form>
            </template>
            <template v-else>
              <div class="list">
                <div class="list-search">
                  <section class="main-search separate">
                    <section class="search-inner">
                      <el-row>
                        <el-col :span="8">
                          <section class="search-inner-item">
                            <div class="item-label">页面名称</div>
                            <el-input
                              v-model.trim="listQuery.pageName"
                              style="width: 90%;"
                              class="filter-item"
                              placeholder="请输入页面名称搜索"
                            />
                          </section>
                        </el-col>
                        <el-col :span="8">
                          <section class="search-inner-item">
                            <div class="item-label">页面标识</div>
                            <el-input
                              v-model.trim="listQuery.pageCode"
                              style="width: 90%;"
                              class="filter-item"
                              placeholder="请输入页面标识搜索"
                            />
                          </section>
                        </el-col>
                        <el-col :span="8">
                          <section class="search-inner-item">
                            <div class="item-label">页面地址</div>
                            <el-input
                              v-model.trim="listQuery.pageRoute"
                              style="width: 90%;"
                              class="filter-item"
                              placeholder="请输入页面地址搜索"
                            />
                          </section>
                        </el-col>
                      </el-row>
                    </section>
                    <section class="search-btn">
                      <el-button type="primary" @click="getList">搜索</el-button>
                      <el-button type="primary" @click="handleReset">重置</el-button>
                    </section>
                  </section>
                </div>

                <p v-if="current && current.pageName!==''" style="color:red;">当前选择：{{ current.pageName }}</p>
                <div class="list-box">
                  <v-table
                    :list="links"
                    tag="link"
                    :list-loading="listLoading"
                    :selection="false"
                  >
                    <el-table-column
                      label="操作"
                      fixed="right"
                      align="center"
                      min-width="50"
                      class-name="small-padding fixed-width"
                    >
                      <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="handleSelect(scope.row)">选择</el-button>
                      </template>
                    </el-table-column>

                  </v-table>
                </div>
                <div v-show="total>0" class="list-bottom">
                  <pagination
                    v-show="total>0"
                    :total="total"
                    :page.sync="listQuery.page"
                    :limit.sync="listQuery.pageSize"
                    @pagination="getList"
                  />
                </div>
              </div>
              <!--              <ul>-->
              <!--                <li-->
              <!--                  v-for="(item,i) in links"-->
              <!--                  :key="item.pageRoute+1"-->
              <!--                  :class="{'active': item.pageRoute == current.pageRoute}"-->
              <!--                  @click="handleSelect(item)"-->
              <!--                >{{ item.pageName }}-->
              <!--                </li>-->
              <!--              </ul>-->
            </template>
          </el-main>
        </el-container>
      </section>
      <section slot="footer">
        <el-button size="small" @click="handleCancel">取消</el-button>
        <el-button :loading="loading" size="small" type="primary" @click="handleComit">确定</el-button>
      </section>
    </CommonDialog>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      append-to-body
      :title="'设置跳转参数'"
      :visible.sync="paramVisible"
      center
      width="750px"
    >
      <el-table
        :data="paramsList"
        style="width: 90%;margin: 0 auto;"
      >
        <el-table-column
          label="参数名"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.keyName" placeholder="请输入" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column
          label="标识"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.keyCode" placeholder="请输入" :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column
          label="值类型"
        >
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.type">
              <el-radio label="1">固定值</el-radio>
              <el-radio label="2">变量值</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column
          label="参数值"
        >
          <template slot-scope="scope">
            <el-input v-if="scope.row.type==='1'" v-model="scope.row.keyValue" placeholder="请输入" />
            <el-select v-else-if="scope.row.type==='2'" v-model="scope.row.keyValue" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.code"
                :label="getName(item)"
                :value="item.code"
              />
            </el-select>

          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" @click="paramVisible = false">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="paramFun()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CommonDialog from '@/components/Dialog'
import { queryFixedPage, queryCustomPageInfo } from '@/components/CustomPage/api'
import { getVar } from '@/components/CustomPage/apps/widget/mixins'
import elDragDialog from '@/directive/el-drag-dialog'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'

export default {
  name: 'PagemakerLinks',
  components: { Pagination, VTable, CommonDialog },
  directives: { elDragDialog },
  props: {
    title: {
      type: String,
      default: ''
    },
    type: {
      type: [String, Number],
      default: ''
    },
    compVar: {
      type: Array,
      default: () => {
        return []
      }
    },
    pageVar: {
      type: Array,
      default: () => {
        return []
      }
    },
    fn: {
      type: Function,
      default: () => {
      }
    },
    cn: {
      type: Function,
      default: () => {
        return false
      }
    },
    upValue: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      listQuery: {
        page: 1,
        pageSize: 10,
        pageName: '',
        pageCode: '',
        pageRoute: ''
      },
      total: 0,
      listLoading: false,
      options: [],
      options4all: [
        {
          label: '页面变量',
          options: []
        },
        {
          label: '组件变量',
          options: []
        }
      ],
      paramVisible: false,
      loading: false,
      form: {
        name: '',
        link: ''
      },
      rules: {
        name: [{ required: true, message: '请输入链接名称', trigger: 'blur' }],
        link: [{ required: true, message: '请输入链接地址', trigger: 'blur' }]
      },
      list: [
        {
          label: '自定义页面',
          value: 'other',
          list: []
        },
        {
          label: '外部链接',
          value: 'outside'
        },
        {
          label: '内部链接',
          value: 'inside',
          list: []
        }
      ],
      active: 'other',
      current: {},
      links: [],
      paramsList: []
    }
  },
  async created() {
    this.options = [...this.pageVar, ...this.compVar]
    this.active = this.upValue?.type || 'other'
    this.current.pageRoute = this.upValue?.link
    this.current.pageName = this.upValue?.name
    this.paramsList = this.upValue?.params !== '' && this.upValue?.params !== undefined ? JSON.parse(this.upValue.params) : []
    if (this.paramsList.length > 0) {
      this.paramVisible = true
    }
    if (this.active == 'outside') {
      this.form.name = this.upValue?.name
      this.form.link = this.upValue?.link
    }
    this.getList()
  },
  methods: {
    handleCancel() {
      if (this.cn()) {
        this.cn()
      } else {
        this.$emit('close')
      }
    },
    handleReset() {
      this.listQuery = {
        page: 1,
        pageSize: 10,
        pageName: '',
        pageCode: '',
        pageRoute: ''
      }
    },
    getList() {
      if (this.active === 'other') {
        this.queryCustomPageInfo()
      } else if (this.active === 'inside') {
        this.queryFixedPage()
      }
    },
    getName(item) {
      const before = getVar(item.code, 0) === 'route' ? '（页面变量）' : '（组件变量）'
      return before + item.name
    },
    paramFun() {
      this.paramVisible = false
    },
    init() {
      this.queryFixedPage()
      this.queryCustomPageInfo()
    },

    handleComit() {
      const { active } = this
      if (active == 'outside') {
        this.$refs.form.validate((flag) => {
          if (flag) {
            this.loading = true
            const { name, link } = this.form
            this.fn && this.fn(active, name, link)
            // this.$emit('close')
            this.handleCancel()
          }
        })
      } else {
        const { pageName, pageRoute } = this.current
        let params = ''
        if (this.paramsList.length > 0) {
          params = JSON.stringify(this.paramsList)
        }
        this.fn && this.fn(active, pageName, pageRoute, params)
        // this.$emit('close')
        this.handleCancel()
      }
    },

    handleToggle({ value, list }) {
      this.active = value
      this.getList()
      this.paramsList = []
      this.total = 0
      // if (value != 'outside') {
      //   this.links = Object.assign([], list)
      // } else {
      //   this.paramsList = []
      // }
    },
    // 切换页面事件
    handleSelect(v) {
      // 自定义页面
      let allParam = []
      if (this.active === 'other') {
        let params = []
        try {
          params = JSON.parse(v.config).pageVar
        } catch (e) {
          params = []
        }
        for (let i = 0; i < params.length; i++) {
          allParam.push({
            keyName: params[i].name,
            keyCode: params[i].code
          })
        }
      } else {
        // 登记的页面
        allParam = v.pageParam ? JSON.parse(v.pageParam) : []
      }
      if (allParam.length > 0) {
        for (let i = 0; i < allParam.length; i++) {
          allParam[i].type = '1'
          allParam[i].keyValue = ''
        }
        this.$set(this, 'paramsList', allParam)
        this.paramVisible = true
      }
      this.current = Object.assign({}, v)
    },

    /**
     * 查询固定页面列表
     * @returns {Promise<unknown>}
     */
    queryFixedPage() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        const obj = Object.assign({ registerType: 1 }, this.listQuery)
        queryFixedPage(obj).then(res => {
          this.links = res.data.data.rows || []
          this.total = res.data.data.total || 0
          loading.close()
        }).catch(err => {
          console.warn(err)
          loading.close()
        })
      })
    },
    /**
     * 查询静态页面列表
     * @returns {Promise<unknown>}
     */
    queryCustomPageInfo() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryCustomPageInfo(this.listQuery).then(res => {
          this.links = res.data.data.rows || []
          this.total = res.data.data.total || 0
          loading.close()
        }).catch(err => {
          console.warn(err)
          loading.close()
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/var.scss';
@import '@/styles/utility/shadow.scss';

.pagemaker-links {
  /deep/ {
    .content {
      height: 550px;

      > section {
        display: flex;
        height: 100%;
      }
    }
  }

  .el-aside {
    @include boxShadow(1);

    > ul {
      margin: 0;
      padding: 0;
      list-style: none;

      > li {
        line-height: 50px;
        text-align: center;
        cursor: pointer;

        &.active {
          color: #fff;
          @include bg-color($mainColor);
        }
      }
    }
  }

  .el-main {
    .tip {
      font-size: 12px;
      color: #f3f3f3;
      line-height: 20px;
      padding-left: 80px;
    }

    > ul {
      list-style: none;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin: 0;
      padding: 0;

      > li {
        height: 30px;
        border: 1px solid #333333;
        border-radius: 2px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 10px;
        font-size: 12px;
        margin-right: 10px;
        margin-bottom: 10px;
        transition: all ease-in-out 0.3s;
        cursor: pointer;

        &.active {
          @include font-color($mainColor);
          @include border-color(1px, solid, $mainColor);
        }
      }
    }

    .list {
      height: 100%;
      display: flex;
      flex-direction: column;

      .list-search {
        .main-search {
          background-color: #fff;
          padding: 0 10px;

          .svg-container {
            padding: 0 5px 0 10px;
            color: #bfced6;
            vertical-align: middle;
            display: inline-block;
          }

          .search-input {
            width: 60%;
            position: relative;

            &:after {
              content: '';
              position: absolute;
              left: -25px;
              right: 0;
              bottom: 8px;
              height: 1px;
              background: rgba(226, 227, 232, 1);
            }

            input {
              outline: none;
              background: transparent;
              border: none;
              outline: medium;
              padding: 0;

              &:focus {
                outline: none;
                background-color: transparent;
              }
            }
          }

          .search-btn {
            display: inline-block;
            float: right;

            .el-button.is-round {
              padding: 10px 30px;
              margin-right: 34px;
            }

            .search-more {
              font-size: 14px;
              font-weight: 500;
              @include font-color($mainColor);
              cursor: pointer;
              margin-left: 10px;
            }
          }

          &.merge {
            height: 50px;
            line-height: 50px;
          }

          &.separate {
            .search-inner {
              padding-top: 10px;

              .search-inner-item {
                .item-label {
                  height: 30px;
                  line-height: 30px;
                  font-size: 14px;
                  color: #a6a6a6;
                  font-weight: 400;
                }

                .el-input {
                  position: relative;

                  &.el-date-editor input {
                    padding-left: 30px;
                  }

                  .el-input__inner {
                    border: none;
                    padding: 0;
                  }

                  &:after {
                    content: '';
                    height: 1px;
                    background-color: #e2e3e8;
                    position: absolute;
                    left: 0;
                    right: 0;
                    bottom: 0;
                  }
                }
              }
            }

            .search-btn {
              text-align: center;
              display: block;
              float: none;
              height: 56px;
              line-height: 56px;
            }
          }
        }
      }

      .list-box {
        flex: 1;
        overflow-y: auto;
      }

      .list-bottom {
        height: 60px;
      }
    }
  }
}
</style>
